package com.android.gui;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.android.controller.Controller;
import com.android.gui.CanvasDrawingActivity.DrawingPanel;
import com.android.networking.connection.Connection;
import com.android.networking.message.DataMessage;
import com.android.networking.message.DataPacket;


public class ClientDrawingActivity extends  Activity   {
	private ArrayList<Path> _graphics = new ArrayList<Path>();
	private Paint mPaint;
	private  String clientMessage;
	static ServerSocket providerSocket;
	//Socket connection = null;
	static ObjectOutputStream out;
	BufferedReader in;
	String message;
	private static TextView serverStatus;
	private static SurfaceView sv;
    static int col = 0xffffffff;
   
    //
    LinearLayout linear, linear1;
    TextView text1,text2,text3,text4,text5;
    TableLayout _table;
    TableRow r1, r2, r3,r4;
   
    Button b1, b2, b3;   
	Controller cont = new Controller();
	ArrayList<MotionEvent> p = new ArrayList<MotionEvent>();
	int pathcount = 0;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _table = new TableLayout(this);
        mPaint = new Paint();   
        r1 = new TableRow(this);
        text1 = new TextView(this);
        text1.setText("This is text1!");
        text2 = new TextView(this);
        text2.setText("This is text2!");
   
        r1.addView(text1);
        r1.addView(text2); 
        r2 = new TableRow(this);
        text3 = new TextView(this);
        text3.setText("This is text3!");
        text4 = new TextView(this);
        text4.setText("This text4!");
        r2.addView(text3);
        r2.addView(text4); 
       
        linear = new LinearLayout(this);
        linear.setOrientation(LinearLayout.VERTICAL);
        sv = new SurfaceView(this);
        sv = new DrawingPanel(this);
       
       
        linear.addView(sv,480,600);
       
        r4 = new TableRow(this);
        r4.setOrientation(TableLayout.HORIZONTAL);
        b1 = new Button(this);
        b1.setText("Button1");
        b1.setMinimumWidth(235);
        b2 = new Button(this);
        b2.setText("Button2");
        b2.setMinimumWidth(235);
        b1.setText("Eraser");
        b2.setText("Clear");
       
        r4.addView(b1);
        r4.addView(b2);
       
        _table.addView(r1);
        _table.addView(r2);
        _table.addView(linear);
        _table.addView(r4);
       
       
       
        setContentView(_table);
        sv.setDrawingCacheEnabled(true);
        
        ClientDrawingActivity obj = new ClientDrawingActivity();
       //obj.createConnection();
        DrawingPanel dp = (com.android.gui.ClientDrawingActivity.DrawingPanel) sv;
        if(cont.test()){
	      //  setContentView(dp);
	        Log.d("Draw","In onCreate");
	        //mPaint = new Paint();
	        mPaint.setDither(true);   
	        mPaint.setColor(0xFFFFFFFF);
	        mPaint.setStyle(Paint.Style.STROKE);
	        mPaint.setStrokeJoin(Paint.Join.ROUND);
	        mPaint.setStrokeCap(Paint.Cap.ROUND);
	        mPaint.setStrokeWidth(3);
	        dp.onDataReceived();
        }
		
	}
	
	

	protected void onStop(){
		Log.d("Draw:","Bye Bye!!!");
		try{
			in.close();
			out.close();
		providerSocket.close();
		}catch(Exception ex){}
   		System.exit(0);
	}
	 
	class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback {
		private DrawingThread _thread;
		private Path path;
				
		public DrawingPanel(Context context) {
			super(context);
            getHolder().addCallback(this);
            _thread = new DrawingThread(getHolder(), this);
            Log.d("Draw","In DrawingPanel Constructor");
		}
		
		
		public boolean onDataReceived(){
			Connection conn = Connection.getInstanceOfConnection();
			Socket csocket;
			csocket = conn.getClientSocket();
			while(true)
			{
				
				if(csocket==null)
				{
					continue;
				}
				else
				{
					break;
				}
			}
			try {
				 Socket csock = conn.getClientSocket(); 
				 in = new BufferedReader(new InputStreamReader(
                         csock.getInputStream()));
				 	
				 String cstr = in.readLine();
				 DataMessage dm = DataMessage.getDataMessageInstance(cstr);
				 DataPacket cdp = dm.getLocalPack(); 
			
					synchronized (_thread.getSurfaceHolder()) {
			            //	if(event.getAction() == MotionEvent.ACTION_DOWN){
			            		path = new Path();
			            		int ci=0;
			            		for (ci = 0; ci<cdp.getPointsPathLen(); ci++)
			            		{
			            			MotionEvent event = (MotionEvent) cdp.getPointPath().get(ci);
			            			path.moveTo(event.getX(), event.getY());
			            			path.lineTo(event.getX(), event.getY());
			            			_graphics.add(path);
			            		}
						}
				
				return true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
				return true;
		}
		
   /*     public boolean onTouchEvent(MotionEvent event) {
        	Log.d("Draw","In onTouchEvent");
            synchronized (_thread.getSurfaceHolder()) {
            	if(event.getAction() == MotionEvent.ACTION_DOWN){
            		path = new Path();
            		path.moveTo(event.getX(), event.getY());
            		path.lineTo(event.getX(), event.getY());
            		_graphics.add(path);
            	}else if(event.getAction() == MotionEvent.ACTION_MOVE){
            		path.lineTo(event.getX(), event.getY());
            		
            	}else if(event.getAction() == MotionEvent.ACTION_UP){
            		path.lineTo(event.getX(), event.getY());
            		//_graphics.add(path);
            	}
            	if(pathcount<50){
            		p.add(event);
					pathcount++;
            	}else{
					pathcount =0;
					cont.sendMessage(p);
				}
            	return true;
            }
            
		}
		
	*/	@Override
        public void onDraw(Canvas canvas) {
			for (Path path : _graphics) {
				//canvas.drawPoint(graphic.x, graphic.y, mPaint);
					canvas.drawPath(path, mPaint);
			}
		}
		
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
								   int height) {
			// TODO Auto-generated method stub
			
		}
		
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			Log.d("Draw","In surfaceCreated");
			_thread.setRunning(true);
            _thread.start();
		}
		
		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			Log.d("Draw","In surfaceDestroyed");
			boolean retry = true;
            _thread.setRunning(false);
            while (retry) {
                try {
                    _thread.join();
                    retry = false;
                } catch (InterruptedException e) {
                    // we will try it again and again...
                }
            }
		}
	}
	
	class DrawingThread extends Thread {
        private SurfaceHolder _surfaceHolder;
        private DrawingPanel _panel;
        private boolean _run = false;
		
        public DrawingThread(SurfaceHolder surfaceHolder, DrawingPanel panel) {
        	Log.d("Draw","In DrawingThread Constructor");
            _surfaceHolder = surfaceHolder;
            _panel = panel;
        }
		
        public void setRunning(boolean run) {
            _run = run;
        }
		
        public SurfaceHolder getSurfaceHolder() {
            return _surfaceHolder;
        }
		
        @Override
        public void run() {
            Canvas c;
            while (_run) {
                c = null;
                try {
                    c = _surfaceHolder.lockCanvas(null);
                    synchronized (_surfaceHolder) {
                        _panel.onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        _surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}
